package cn.webNews.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.taglibs.standard.tag.common.sql.DataSourceUtil;
import org.omg.CORBA.PUBLIC_MEMBER;

import cn.webNews.bean.Detail;
import cn.webNews.util.DataSourceUitls;
import cn.webNews.util.Page;

public class BaseDaoImpl {
	public int executeUpdate(String sql,Object[] objs){
		try {
			QueryRunner runner=new QueryRunner(DataSourceUitls.getDataSource());
			return runner.update(sql, objs);
			
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
		
	}
	
	public List findAll(String sql,Class clazz){
		try {
			QueryRunner runner=new  QueryRunner(DataSourceUitls.getDataSource());
			return runner.query(sql, new BeanListHandler(clazz));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	protected void execQuery(Page page,String sql,List parms){
		try {
			QueryRunner runner=new QueryRunner(DataSourceUitls.getDataSource());
			String countSql=sql.toUpperCase().replaceAll("select.+?from","select count(*) from ");
			Long total=runner.query(countSql, new ResultSetHandler(){
				public Object handle(ResultSet rs) throws SQLException{
					rs.next();
					return rs.getLong(1);
					
				}
			},parms.toArray());
			
			page.setTotal(total);
			String limit=" limit ?,? ";
			
			parms.add((page.getPage()-1)*page.getPageSize());
			parms.add(page.getPageSize());
			List list=runner.query(sql+limit,new BeanListHandler(Detail.class),parms.toArray());
			page.setLsit(list);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	
}
